#include "WeaponBank.h"
#include "GameConfig.h"
#include "Config.h"
#include "pugixml.hpp"
#include "WeaponFactory.h"

using namespace pugi;

WeaponBank::WeaponBank(void)
{
	_listWeaponFactory = NULL;
}


WeaponBank::~WeaponBank(void)
{
	CC_SAFE_RELEASE(_listWeaponFactory);
}

void WeaponBank::initBank()
{
	setWeaponFactories(CCDictionary::create());

	// init Factories
	string data = string(dynamic_cast<CCString*>(GameConfig::sharedGameConfig()->getConfigData()->objectForKey(CONFIG_WEAPONS))->getCString());

	xml_document doc;
	xml_parse_result result = doc.load(data.c_str());
	CCAssert(result.status == status_ok, "FAILD");

	xml_node node = doc.child("Root").child("Weapons");

	for (xml_node i = node.child("Weapon"); i; i = i.next_sibling("Weapon"))
	{
		WeaponFactory* wFactory = WeaponFactory::create();
		wFactory->parseXml(i);
		_listWeaponFactory->setObject(wFactory, wFactory->getId()->getCString());
	}
}

void WeaponBank::clearBank()
{
	delete _instance;
	_instance = NULL;
}

WeaponBank* WeaponBank::sharedWeaponBank()
{
	if (!_instance)
		_instance = new WeaponBank();
	return _instance;
}

Weapon* WeaponBank::getWeapon( char* type )
{
	WeaponFactory* fa = dynamic_cast<WeaponFactory*>(_listWeaponFactory->objectForKey(type));
	if (fa)
		return fa->createWeapon();
	return NULL;
}

WeaponBank* WeaponBank::_instance = NULL;
